package org.hfy.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.hfy.dto.warehouse.InventoryAdjustmentDTO;
import org.hfy.dto.warehouse.InventoryQueryDTO;
import org.hfy.entity.Inventory;
import org.hfy.mapper.InventoryMapper;
import org.hfy.service.InventoryService;
import org.hfy.exception.WarehouseException;

import java.util.List;

/**
 * 库存管理服务实现类
 * 
 * @author hfy
 * @version 1.0
 */
@Service
public class InventoryServiceImpl extends ServiceImpl<InventoryMapper, Inventory> implements InventoryService {

    @Override
    public IPage<Inventory> getInventoryPage(InventoryQueryDTO queryDTO) {
        Page<Inventory> page = new Page<>(queryDTO.getCurrent(), queryDTO.getSize());
        return baseMapper.selectInventoryPage(page, queryDTO);
    }

    @Override
    public Inventory getByFactoryNo(String factoryNo) {
        return baseMapper.selectByFactoryNo(factoryNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Inventory adjustInventory(Long id, InventoryAdjustmentDTO adjustmentDTO) {
        Inventory inventory = getById(id);
        if (inventory == null) {
            throw new WarehouseException.DataNotFoundException("库存记录", id);
        }

        // 调整库存数量
        int newQuantity = inventory.getCurrentStockQuantity() + adjustmentDTO.getAdjustmentQuantity();
        if (newQuantity < 0) {
            throw new WarehouseException.QuantityValidationException(
                String.format("调整后库存数量不能为负数，当前库存：%d，调整数量：%d", 
                inventory.getCurrentStockQuantity(), adjustmentDTO.getAdjustmentQuantity()));
        }

        inventory.setCurrentStockQuantity(newQuantity);
        
        // 更新库存状态
        updateInventoryStatus(inventory);
        
        updateById(inventory);
        
        // 这里可以记录库存调整日志
        // TODO: 创建库存调整记录表并记录调整历史
        
        return inventory;
    }

    @Override
    public void updateStockQuantity(String factoryNo, Integer inboundQuantity, Integer outboundQuantity) {
        try {
            // 使用数据库原子操作更新库存数量
            baseMapper.updateStockQuantity(factoryNo, inboundQuantity, outboundQuantity);
            
            // 获取更新后的库存信息进行状态检查
            Inventory inventory = getByFactoryNo(factoryNo);
            if (inventory != null) {
                // 自动更新库存状态
                updateInventoryStatus(inventory);
                updateById(inventory);
                
                // 触发预警检查
                checkAndSendWarning(inventory);
            } else {
                throw new WarehouseException.DataNotFoundException("库存记录", factoryNo);
            }
        } catch (Exception e) {
            if (e instanceof WarehouseException) {
                throw e;
            }
            throw new WarehouseException.ConcurrentOperationException("库存数量更新");
        }
    }

    @Override
    public List<Inventory> getLowStockItems() {
        return baseMapper.selectLowStockItems();
    }

    @Override
    @Scheduled(cron = "0 0 9 * * ?") // 每天9点检查
    public void checkStockWarning() {
        List<Inventory> lowStockItems = getLowStockItems();
        for (Inventory item : lowStockItems) {
            // 这里可以发送预警通知
            // TODO: 实现预警通知功能 (邮件、短信、系统消息等)
            System.out.println("库存预警: 厂内编号=" + item.getFactoryNo() + 
                             ", 产品=" + item.getProductName() + 
                             ", 当前库存=" + item.getCurrentStockQuantity());
        }
    }

    /**
     * 更新库存状态
     */
    private void updateInventoryStatus(Inventory inventory) {
        int currentStock = inventory.getCurrentStockQuantity();
        int minStock = inventory.getMinStockQuantity() != null ? inventory.getMinStockQuantity() : 5;
        
        String newStatus;
        if (currentStock <= 0) {
            newStatus = "无库存";
        } else if (currentStock <= minStock) {
            newStatus = "预警";
        } else {
            newStatus = "有库存";
        }
        
        // 只有状态发生变化时才更新
        if (!newStatus.equals(inventory.getStatus())) {
            String oldStatus = inventory.getStatus();
            inventory.setStatus(newStatus);
            
            // 记录状态变更日志
            logStatusChange(inventory, oldStatus, newStatus, "库存数量变化触发状态更新");
        }
    }

    /**
     * 检查并发送预警
     */
    private void checkAndSendWarning(Inventory inventory) {
        if ("预警".equals(inventory.getStatus()) || "无库存".equals(inventory.getStatus())) {
            // 发送预警通知
            System.out.println("【库存预警】厂内编号: " + inventory.getFactoryNo() +
                             ", 产品: " + inventory.getProductName() +
                             ", 当前库存: " + inventory.getCurrentStockQuantity() +
                             ", 预警线: " + (inventory.getMinStockQuantity() != null ? inventory.getMinStockQuantity() : 5) +
                             ", 状态: " + inventory.getStatus());
            
            // TODO: 实现邮件/短信/系统消息预警功能
        }
    }

    /**
     * 记录状态变更日志
     */
    private void logStatusChange(Inventory inventory, String fromStatus, String toStatus, String reason) {
        // TODO: 实现状态变更日志记录
        System.out.println("【状态变更】厂内编号: " + inventory.getFactoryNo() +
                         ", 从 [" + fromStatus + "] 变更为 [" + toStatus + "]" +
                         ", 原因: " + reason);
    }
} 